<?php
/**
 *    1. 控制器类统一放在Ctrl命名空间
 *    2. 控制器类名统一以Ctrl结尾
 *    3. 控制器负责：(1)参数接收 (2)参数合法性校验 (3)调用业务逻辑层 (4)输出结果
 *    4. 返回错误不要相同，便于快速定位问题
 *    5. 不要直接将idip、经分接口、paas接口、db、Redis错误返回给客户端。错误信息应该经过脱敏处理之后返回友好的提示信息
 *    6. outputJson必须在Ctrl文件里输出，且前面必须要加个return，否则程序还会往下运行
 *    7. 框架使用说明文档：https://ulink.qq.com/ulinksdk/doc/ulink_frame/manual.html
 *    8. 使用过程中遇到任何问题请企业微信联系 ronzheng,smallyang
 */

namespace Ctrl;

use Lib\Base\Common;
use Lib\Base\HttpRequest;
use Lib\Base\L5;
use Lib\Base\Request;
use Lib\Base\Validate;
use Lib\Cache\CoRedis;
use Lib\Cache\RedisAction;
use Lib\Db\Query;
use Lib\Paas\DirtyFilter;
use Lib\Paas\IDIP;
use Lib\Paas\Login;
use Lib\Service\TransOpenId;
use Logic\DemoLogic;


class SwooleDemoCtrl
{
    public function __construct()
    {

    }

    /**
     * DB、Redis查询操作
     */
    public function getUserInfo()
    {
        //参数接收
        $openid = Request::param('iUin');

        //参数校验
        if (!Validate::checkOpenid($openid, 'wq')) {
            return outputJson(-7, '系统繁忙，请稍后再试！');
        }

        //调用Logic层处理业务逻辑
        $demoLg = new DemoLogic();
        $rtnData = $demoLg->getUserInfo($openid);

        //结果输出
        if ($rtnData === false) {
            return outputJson(-8, '系统繁忙，请稍后再试！');
        } else {
            return outputJson(0, 'success', $rtnData);
        }
    }

    /**
     * 脏字过滤
     */
    public function checkDirty()
    {
        //参数获取
        $content = Request::getParam('content');

        //参数校验
        if ($content == '' || \mb_strlen($content) > '10') {
            return outputJson(-9, '内容不能为空且不超过10个字');
        }

        //调用Logic层处理业务逻辑
        $demoLg = new DemoLogic();
        $rtnData = $demoLg->filterDirtyWords($content);

        //结果输出
        outputJson(0, 'success', ['content' => $rtnData]);
    }

    public function hello()
    {
        outputJson(0, 'world');
    }

    /**
     * 测试redis
     */
    public function test_redis()
    {
        $redis = new RedisAction(['groupId' => 0, 'prefix' => 0]);

        $redis->zAdd('key', 1, 'val1');
        $redis->zAdd('key', 0, 'val0');
        $redis->zAdd('key', 5, 'val5');
        $a = $redis->zRange('key', 0, -1); // array(val0, val1, val5)

        $result = $redis->set("test_key2", rand(1, 1000));
        if ($result) {
            $redis->set("test_key3", rand(1, 100));
        }
        $result = $redis->get("test_key3");

        outputJson(0, $result);
    }

    /**
     * 测试协程redis(内部正职专用)
     *
     * @return bool
     * @throws \Exception
     */
    public function test_coRedis()
    {
        //协程redis
        $redisObject = new CoRedis(['groupId' => 0, 'prefix' => 0]);

        if (!$redisObject->redis) {
            return outputJson(-1008, 'redis链接失败');
        }

        $redis = $redisObject->redis;
        $redis->zAdd('key', 1, 'val1');
        $redis->zAdd('key', 0, 'val0');
        $redis->zAdd('key', 5, 'val5');
        $a = $redis->zRange('key', 0, -1); // array(val0, val1, val5)

        $result = $redis->set("test_key2", rand(1, 1000));
        if ($result) {
            $redis->set("test_key3", rand(1, 100));
        }
        $result = $redis->get("test_key3");
        outputJson(0, $result);
    }

    /**
     * 测试db
     */
    public function test_db()
    {
        $query = new Query();

        //select 返回的数组格式为： $result['rows' => 9, "data" => [...]]
        $result = $query->table('tbUserCoupon')->where('id', '>', 1)->select(['id', 'openId']);
        $result = $query->table('tbUserCoupon')->where(['openId' => '2A496F7A47579A913E89789C8081DA11','rate' => '1'])->select();

        //insert
        $rtnData = $query->table('tbUserCoupon')->insertGetId(['openId' => '2A496F7A47579A913E89789C8081DA11', 'status' => '1']);

        //delete
        $a = $query->table('tbUserCoupon')->where('id', 1)->delete();

        //update
        $b = $query->table('tbUserCoupon')->where('openId', '2A496F7A47579A913E89789C8081DA11')->update(['rate' => '90', 'status' => 0]);
        $b = $query->table('tbInvite')->where(['inviteUin' => '123432', 'status' => 0])->update(['status' => 1]);

        //count
        $info = $query->table('tbInvite')->where(['inviteUin' => '123', 'status' => 0])->count();
        $count =  $info['data'][0]['cnt'];

        //uin = 1234 or  inviteUin = 1234
        $info = $query->table('tbInviteGroup')->where('uin', '1234')->whereOr('inviteUin', '1234')->find('uin,nickname,headUrl,inviteUin,nickname2,headUrl2');

        outputJson(0, 'ok', [$result, $rtnData, $a, $b, $c]);
    }

    /**
     * 测试token
     */
    public function test_genToken()
    {
        $data = [
            'openid' => '1',
            'area' => '1',
            'platid' => '1',
            'partition' => '1',
            'roleId' => '1'
        ];

        $salt = [
            'tokenKey' => 'sdfssdwerw1xkkss'
        ];

        $md5Str = Common::genToken($data, $salt);
        outputJson(0, 'ok', $md5Str);
    }

    /**
     * 测试获取随机数
     */
    public function test_getRandStr()
    {
        $md5Str = Common::getRandStr(rand(6, 20), rand(1, 3), rand(0, 1));
        outputJson(0, 'ok', $md5Str);
    }

    /**
     * 测试time33
     */
    public function test_time33()
    {
        $md5Str = Common::time33(rand(1, 20));
        outputJson(0, 'ok', $md5Str);
    }

    /**
     * getAcctype
     */
    public function test_getAcctype()
    {
        $md5Str = Common::getAcctype();
        outputJson(0, 'ok', $md5Str);
    }

    /**
     * cookie2Str
     */
    public function test_cookie2Str()
    {
        $md5Str = Common::cookie2Str();
        outputJson(0, 'ok', $md5Str);
    }

    /**
     * 加密解密
     */
    public function test_encryptData()
    {
        $data = [
            'openid' => '1',
            'area' => '1',
            'platid' => '1',
            'partition' => '1',
            'roleId' => '1'
        ];
        $md5Str = Common::encryptData($data, '123');

        $b = Common::decryptData($md5Str, '123');
        outputJson(0, 'ok', [$md5Str, $b]);
    }

    /**
     * 字符编码转换
     */
    public function test_charsetConvert()
    {
        $str1 = Common::charsetConvert("我们", 'UTF-8', 'GBK');
        $str2 = Common::charsetConvert($str1, 'GBK', 'UTF-8');

        outputJson(0, 'ok', [$str2]);
    }

    /**
     * getClientIp
     */
    public function test_getClientIp()
    {
        $str1 = Common::getClientIp();

        outputJson(0, 'ok', [$str1]);
    }

    /**
     * http get请求
     */
    public function test_http_get()
    {
        $httpCoRequest = new HttpRequest();
        $a = $httpCoRequest->get("http://127.0.0.1:10271/?c=Demo&a=hello", []);
        outputJson(0, 'ok', [$a]);
    }

    /**
     * http post 请求
     */
    public function test_http_post()
    {
        //$url = 'http://129.0.0.1:10271/?c=Demo&a=hello';
        $url = 'http://100.117.44.38/x1/3209/34174&182986?dmsourceid=dZVC6efHRlaQtuTn&openid=F5339F11A2B415CB487ADD433EDD56CA&roleid=8468174674340124271';
//        $param = [];
//        $obj = new \HTTPRequest();
//        $obj->post($url, $param, $data);

        //测试环境，swoole 是2.x的会有问题，会假死。线上无影响
        $httpCoRequest = new HttpRequest();
        $data = $httpCoRequest->post($url, []);
        outputJson(0, 'ok', $data);
    }

    /**
     * L5
     */
    public function test_l5()
    {
        $l5Req = L5::getHostInfo(64253697, 65536);
        outputJson(0, 'ok', $l5Req);
    }

    /**
     * IDIP
     *
     * @return bool
     */
    public function test_idip()
    {
        //王者荣耀-查询用户基本信息：cmd=10162000&area=xx&platid=xx&partition=xx&openid=xx
        $cmdParams = [
            'cmd' => 10001055,
            'area' => '1',
            'openid' => 'oKdX1jkaz8lksSV1vBtu78jqhZTE',
            'serviceType' => "WP"
        ];

        $idip = new IDIP();
        $rtnData = $idip->getData($cmdParams);
        if ($rtnData['result'] == 0) {
            //idip查询正确
            return outputJson(0, 'ok', $rtnData);
        } else {
            //idip查询异常
            return outputJson(0, 'ok', $rtnData);
        }

        //内部调用
        $a = "cmd=10001055&openid=oKdX1jkaz8lksSV1vBtu78jqhZTE&area=1";

        $idIp = new \OSSIDIP(Request::getRequest());
        $ret = $idIp->query($a, $res);

        return outputJson(0, 'ok', [$res, $ret]);
    }

    /**
     * 脏词
     */
    public function test_checkDirtyWord()
    {
        $DirtyFilter = new DirtyFilter();
        $name = "胡锦涛123";
        $b = $DirtyFilter->checkDirtyWord($name, $result);
        outputJson(0, 'ok', [$result, $b]);
    }

    /**
     * 检测登陆
     */
    public function test_login()
    {
        $login = new Login();
        $a = $login->checkLogin();
        outputJson(0, 'ok', [$a]);
    }

    /**
     * openid转uin
     */
    public function test_openid_2_uin()
    {
        $OIDBOpenInfo = new TransOpenId();

        $uin = $OIDBOpenInfo->OpenID2Uin('E54A38ECE5AE7CAEF640753865AA74A8', '1108720835');

        outputJson(0, 'ok', $uin);
    }

    /**
     * hello
     */
    public function test_hello()
    {
        recordLog('AMS instance id cannot be empty!');
        recordLog('222');
        outputJson(0, 'ok');
    }

    /**
     * log分类
     */
    public function test_log()
    {
        recordLog('红色警告', __FILE__, __LINE__, LP_ERROR);
        recordLog('蓝色', __FILE__, __LINE__, LP_INFO);
        recordLog('黑色');
        outputJson(0, 'ok');
    }
}
